﻿using System.Net.WebSockets;
using Manager.Database;
using Manager.Model;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Minio;
using Minio.DataModel.Args;

namespace Manager.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class FileUploadController : ControllerBase
    {
        private readonly PCCSContext _context;
        private readonly MinioClient _minioClient;

        public FileUploadController(PCCSContext context)
        {
            _context = context;
            _minioClient = (MinioClient?)new MinioClient()
                .WithEndpoint("139.196.170.188:9000")
                .WithCredentials("kecheng", "lkclkclkc")
                .Build();
        }



        [HttpGet("getlunbo")]
        public async Task<ObjectResult> GetImages()
        {
            var images = await _context.images.Take(3).ToListAsync();
            return new ObjectResult(images);
        }


        [HttpDelete("deletelunbo")]
        public ObjectResult DeleteImages()
        {
            _context.images.RemoveRange(_context.images);
            _context.SaveChanges();
            return new ObjectResult("删除成功");
        }


        /// <summary>
        /// 文件上传接口
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost("upload")]
        public async Task<ObjectResult> UploadFile(IFormFile file)
        {
            if (file == null || file.Length == 0)
            {
                return new ObjectResult(new { success = false, msg = "文件不能为空" });
            }

            // MinIO 存储桶名称
            string bucketName = "blacket";
            string objectName = Guid.NewGuid().ToString() + Path.GetExtension(file.FileName); // 使用 GUID 确保文件名唯一

            try
            {
                // 检查存储桶是否存在，如果不存在则创建
                var beArgs = new BucketExistsArgs().WithBucket(bucketName);
                bool found = await _minioClient.BucketExistsAsync(beArgs).ConfigureAwait(false);
                if (!found)
                {
                    var mbArgs = new MakeBucketArgs().WithBucket(bucketName);
                    await _minioClient.MakeBucketAsync(mbArgs).ConfigureAwait(false);
                }

                // 使用文件流直接上传到 MinIO
                using (var stream = file.OpenReadStream())
                {
                    var putObjectArgs = new PutObjectArgs()
                        .WithBucket(bucketName)
                        .WithObject(objectName) // 上传到 MinIO 的对象名称
                        .WithStreamData(stream)
                        .WithObjectSize(file.Length)
                        .WithContentType(file.ContentType);

                    await _minioClient.PutObjectAsync(putObjectArgs).ConfigureAwait(false);
                }


                // 获取 MinIO 文件的 URL
                string minioUrl = "http://139.196.170.188:9000";
                var fileUrl = $"{minioUrl}/{bucketName}/{objectName}";

                // 保存图片信息到数据库
                Image image = new Image()
                {
                    url = fileUrl,
                    img = fileUrl
                };

                _context.images.Add(image);
                await _context.SaveChangesAsync();

                return new ObjectResult(new
                {
                    success = true,
                    msg = "上传成功",
                    filePath = fileUrl
                });
            }
            catch (Exception ex)
            {
                // 处理异常
                return new ObjectResult(new { success = false, msg = "上传失败", error = ex.Message });
            }
        }

    }
}
